/**
 * 封装全局接口请求axios函数
 */

import axios from 'axios'
import JSONBIGINT from 'json-bigint'
// 导入store
import store from '../store'
// 导入router实例
import router from '@/router'
const MyAxios = axios.create({
  baseURL: 'http://toutiao-app.itheima.net/v1_0/',
  transformResponse: [function (data) {
    // console.log('1', data)
    // Do whatever you want to transform the data
    // data =>后台返回的JSON字符串
    try {
      // 处理JSON.parse/stringify精度丢失
      // test:console.log(JSONBIGINT.parse('{"a":9223372036854775807}').a.toString(), JSON.parse('{"a":9223372036854775807}'))

      return JSONBIGINT.parse(data)
    } catch (e) {
      return data
    }
  }
  ]

})

// Add a request interceptor
MyAxios.interceptors.request.use(function (config) {
  // Do something before request is sent
  // 请求之前，统一向header中加入token
  // ?.user 处理null
  // 排除登录注册等接口
  if (store.state.user.token && config.url !== 'authorizations') {
    config.headers.Authorization = `Bearer ${store.state.user.token}`
  }
  // 处理接口版本问题
  if (config.url === 'articles') {
    config.baseURL = config.baseURL.replace('v1_0', 'v1_1')
  }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// Add a response interceptor
MyAxios.interceptors.response.use(function (response) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  // 处理和简化返回的数据
  return {
    status: response.status,
    data: response.data?.data
  }
}, async function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  // console.log('error.response', error.response)
  // console.log('拦截器捕获401错误', JSON.stringify(error), error.response, error.response.status)

  const loginConfig = { path: '/login', query: { redirectUrl: router.currentRoute.path } }
  try {
    if (error.response && error.response.status === 401) {
      const { user } = store.state
      if (!user || !user.token || !user.refresh_token) {
        // 跳回登录页面
        router.push(loginConfig)
        return Promise.reject(error)
      }
      // 2. 登录过，token失效了=》刷新token
      // console.log('refresh')
      const { status, data } = await MyAxios.put('authorizations', null, {
        headers: {
          Authorization: `Bearer ${user.refresh_token}`
        }
      })
      // console.log(status, data)
      if (status === 201) {
        // 更新vuex和本地的token
        store.commit('setToken', {
          token: data.token,
          refresh_token: user.refresh_token
        })
        // 继续上次的错误请求(这时token已经刷新了)
        // console.log('error.config', error.config)
        return MyAxios(error.config)
      }
    }
  } catch (error) {
    // 3. refresh_token也失效
    // 跳回登录页面
    router.push(loginConfig)
    return Promise.reject(error)
  }
  return Promise.reject(error)
})

// 封装vue插件
const MyAxiosPlug = function (Vue) {
  // 原型上定义全局方法
  Vue.prototype.request = MyAxios
}
// 导出插件
export { MyAxiosPlug }
// 导出axios
export default MyAxios
